<?php
/**
 * 事件管理绑定
 * @package api\components
 * 
 */

namespace api\components\event;
use yii\base\Component;
use yii\base\Event;
use Yii;


/**
 * @author Johnson
 */
class EventManager extends Component
{
    /**
     * @var array events settings
     */
    public $events = [];

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->attachEvents($this->events);
    }

    /**
     * 绑定配置事件类的方法到对应model的方法上
     * @param array $eventConfig
     */
    public function attachEvents($eventConfig)
    {  
        foreach ($eventConfig as $className => $events) {
            foreach ($events as $eventName => $handlers) {
                foreach ($handlers as $handler) {
                    if (is_array($handler) && is_callable($handler[0])) {
                        $data = isset($handler[1]) ? array_pop($handler) : null;
                        $append = isset($handler[2]) ? array_pop($handler) : null;
                        Event::on($className, $eventName, $handler[0], $data, $append);
                    } else if (is_callable($handler)){
                        Event::on($className, $eventName, $handler);
                    }
                }
            }
        }
    }
}